package com.appspot.diasporajava.manager;

import java.util.List;
import java.util.TreeSet;

import javax.jdo.annotations.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.appspot.diasporajava.dao.PostDao;
import com.appspot.diasporajava.dao.UserDao;
import com.appspot.diasporajava.entities.Post;
import com.appspot.diasporajava.entities.User;
import com.appspot.diasporajava.federation.MarkDown;
import com.appspot.diasporajava.federation.PublicFeed;

@Component
public class FeedManager {

	@Autowired
	UserDao<User, Long> userDao;

	@Autowired
	PublicFeed publicFeed;

	@Autowired
	PostDao<Post, Long> postDao;

	@Transactional
	public void updateFeeds() {
		// for every user
		List<User> users = userDao.list();
		for (User user : users) {
			try{
				updateFeeds(user);
			}catch(Exception e){
				e.printStackTrace();
			}
		}

	}
	
	@Transactional
	public void updateFeeds(User user){
		// find his/her new feeds
		List<Post> posts;
		List<Post> postsOnDb = postDao.findByUserId(user.getId());
		TreeSet<Post> userPosts;
		if (postsOnDb != null) {
			userPosts = new TreeSet<Post>(
					postDao.findByUserId(user.getId()));
		} else {
			userPosts = new TreeSet<Post>();
		}

		if (userPosts != null) {
			Post lastUserPost = userPosts.pollLast();
			if (lastUserPost != null) {
				posts = publicFeed.getPostList(user.getAtomFeed(),
						lastUserPost.getDate());
			} else {
				posts = publicFeed.getPostList(user.getAtomFeed());
			}
		} else {
			posts = publicFeed.getPostList(user.getAtomFeed());
		}

		// save them

		for (Post post : posts) {

			// user.addPost(post);
			post.setUserId(user.getId());
			postDao.create(post);

		}
	}

	public List<Post> getFeeds(Long userId) {
		List<Post> posts = postDao.findByUserId(userId);
		if(posts==null || posts.size()==0){
			updateFeeds();
			posts = postDao.findByUserId(userId);
		}
		return posts;
	}

	public void transform(List<Post> posts) {
		for (Post post : posts) {
			if (post.getHtml() == null) {
				String html = MarkDown.transform(post.getMarkdown());
				post.setHtml(html);
				postDao.update(post);
			}
		}
	}
}
